﻿using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;

namespace IFD2
{
    public partial class Users : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            if (!IsPostBack)
            {
                //非开发环境都需要HPPTS！
                if (Application["DEBUG"].ToString() != "1" && Request.ServerVariables["HTTPS"] != "on")
                {
                    Response.Redirect("https://" + HttpContext.Current.Request.Url.Host + ":" + Convert.ToInt32(Application["HTTPS_PORT"].ToString()).ToString() + Application["WEB_PATH"].ToString() + "/users.aspx");
                    lblError.Text = "Please use HTTPS for safety!";
                    btnSetPwd.Enabled = false;
                    return;
                }
                else
                    btnSetPwd.Enabled = true;

                if (Session["ACL"].ToString().IndexOf("UB4") < 0)
                {
                    Response.Redirect("unauthorized.aspx");
                }
                if (Request.Form["KEY"] != null)
                    lblOffice.Text = Request.Form["KEY"].ToString();

                else if (Request.QueryString["KEY"] != null)
                    lblOffice.Text = Request.QueryString["KEY"].ToString();
                else
                    lblOffice.Text = Session["OFFICE"].ToString();

            }

            btnSetStatus.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            //btnSetPwd.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            //btnSetPwd.Attributes.Add("onclick", "javascript:return checkpwdlevel(MainContent_txtPwd2.value);");
            //btnAdd.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            //btnAddNewUser.Attributes.Add("onclick", "javascript:return checkpwdlevel(MainContent_txtPwd.value);");
        }

        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            GridView1.DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("UB5") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;
            string key;
            //string[] strArray;
            if (Request.Form["KEY"] == null)
            {
                lblError.Text = "Please select the user you want to delete.";
                return;
            }
            key = Request.Form["KEY"];
            //strArray = key.Split('|');

            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_role_delete_user";
                SqlParameter para = cmd.Parameters.AddWithValue("@uid", key);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@office", lblOffice.Text);
                para = cmd.Parameters.AddWithValue("@role", lstRoles.SelectedValue);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@user_office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());
                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                    lblError.Text = "Done.";
                else
                    lblError.Text = "delete failed!";
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }

            GridView1.DataBind();
        }
        protected void btnAddNewUser_Click(object sender, EventArgs e)
        {
            string pwd_hash;
            if (Session["ACL"].ToString().IndexOf("UB5") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            if (lblOffice.Text == Session["OFFICE"].ToString() || Session["OFFICE_TYPE"].ToString() == "COR")
            {

            }
            else
            {
                lblError.Text = "Unauthorized!";
                return;
            }

            txtUid.Text = txtUid.Text.Trim().ToUpper();
            hidP1.Value = hidP1.Value.Trim();
            if (!Pwd_Strength.Check(hidP1.Value, txtUid.Text))
            {
                lblError.Text = "Password is too weak!";
                return;
            }
            //if (txtPwd.Text.Length < 6)
            //{
            //    lblError.Text = "password too short!";
            //    return;
            //}
            string salt="";
            Pwd_Strength.GetSalt(60,ref salt);
            byte[] data = Encoding.ASCII.GetBytes(txtUid.Text + hidP1.Value + salt);
            byte[] result;
            SHA256 sha = new SHA256CryptoServiceProvider();
            result = sha.ComputeHash(data);
            pwd_hash = BitConverter.ToString(result).Replace("-", "");
            //pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPwd.Text, "SHA1");
            int ret_code;
            if (lstRoles.Items.Count == 0)
            {
                lblError.Text = "Please define roles before adding users.";
                return;
            }
            try
            {
                SqlCommand cmd = new SqlCommand("bll_user_new");
                SqlParameter para = cmd.Parameters.AddWithValue("@office", lblOffice.Text);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@role", lstRoles.SelectedValue);
                para = cmd.Parameters.AddWithValue("@uid", txtUid.Text);
                para = cmd.Parameters.AddWithValue("@name", txtName.Text);
                para = cmd.Parameters.AddWithValue("@identification", txtIdentification.Text);
                para = cmd.Parameters.AddWithValue("@pwd", pwd_hash);
                para = cmd.Parameters.AddWithValue("@salt", salt);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@user_office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                    lblError.Text = "Done.";
                else if (ret_code == 1)
                    lblError.Text = "Wrong airline!";
                else if (ret_code == 4)
                    lblError.Text = "authority needed!";
                else if (ret_code == 10)
                    lblError.Text = "Creating new user failed!";
                else if (ret_code == 10)
                    lblError.Text = "Adding user to role failed!";
                else
                    lblError.Text = "Error!" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
            GridView1.DataBind();
        }
        protected void btnAddExistingUser_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("UB5") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;

            SqlCommand cmd = new SqlCommand();
            try
            {
                cmd.CommandText = "bll_role_add_existing_user";
                SqlParameter para = cmd.Parameters.AddWithValue("@office", lblOffice.Text);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@role", lstRoles.SelectedValue);
                para = cmd.Parameters.AddWithValue("@uid", txtUid2.Text);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@user_office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    GridView1.DataBind();
                }
                else if (ret_code == 1)
                    lblError.Text = "wrong airline";
                else if (ret_code == 4)
                    lblError.Text = "authority needed";
                else if (ret_code == 10)
                    lblError.Text = "failed";
                else
                    lblError.Text = "updating failed!" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        protected void btnSetPwd_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("UC4") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            string pwd_hash;
            hidP2.Value = hidP2.Value.Trim();
            if (!Pwd_Strength.Check(hidP2.Value, Session["USER"].ToString()))
            {
                lblError.Text = "Password is too weak!";
                return;
            }
            //if (txtPwd2.Text.Length < 6)
            //{
            //    lblError.Text = "password too short!";
            //    return;
            //}
            string key;
            if (Request.Form["KEY"] == null)
            {
                lblError.Text = "Please select the user.";
                return;
            }
            key = Request.Form["KEY"].Trim().ToUpper();

            string salt = "";
            Pwd_Strength.GetSalt(60, ref salt);

            byte[] data = Encoding.ASCII.GetBytes(key+hidP2.Value+salt);//new byte[20];
            byte[] result;
            SHA256 sha = new SHA256CryptoServiceProvider();
            result = sha.ComputeHash(data);
            pwd_hash = BitConverter.ToString(result).Replace("-", "");
            //pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPwd2.Text, "SHA1");
            lblHashed.Text = pwd_hash;

            int ret_code;
            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_user_reset_password";
                SqlParameter para = cmd.Parameters.AddWithValue("@uid", key);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@pwd", pwd_hash);
                para = cmd.Parameters.AddWithValue("@salt", salt);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@user_office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                    lblError.Text = "Done.";
                else if (ret_code == 1)
                    lblError.Text = "wrong airline";
                else if (ret_code == 4)
                    lblError.Text = "authority needed";
                else if (ret_code == 10)
                    lblError.Text = "failed";
                else
                    lblError.Text = "updating failed!" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
        protected void btnSetStatus_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("UB5") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;
            string key;
            //string[] strArray;
            if (Request.Form["KEY"] == null)
            {
                lblError.Text = "Please select the use.";
                return;
            }
            key = Request.Form["KEY"];
            //strArray = key.Split('|');

            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_user_set_status";
                SqlParameter para = cmd.Parameters.AddWithValue("@uid", key);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@status", lstStatus.SelectedValue);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@user_office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    GridView1.DataBind();
                }
                else if (ret_code == 1)
                    lblError.Text = "wrong airline";
                else if (ret_code == 4)
                    lblError.Text = "authority needed";
                else if (ret_code == 10)
                    lblError.Text = "failed";
                else
                    lblError.Text = "updating failed!" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
                return;
            }

        }

        //protected bool check_pwd(string pwd)
        //{
        //    pwd = pwd.Trim();
        //    if (pwd.Length < 6)
        //    {
        //        lblError.Text = "Password length must be more than 5 characters!";
        //        return false;
        //    }
        //    Regex r1 = new Regex("[a-zA-Z]");
        //    Regex r2 = new Regex("[0-9]");
        //    Regex r3 = new Regex("[^A-Za-z0-9]");
        //    int level=0;
        //    if (r1.IsMatch(pwd))
        //        level++;
        //    if (r2.IsMatch(pwd))
        //        level++;
        //    if (r3.IsMatch(pwd))
        //        level++;
        //    if (level <= 1)
        //    {
        //        lblError.Text = "Password is too weak!";
        //        return false;
        //    }
        //    else
        //        return true;
        //}

        protected void btnFind_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("UB5") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            lblUserName.Text = "";
            lblIdentification.Text = "";
            lblOwnerOffice.Text = "";
            DataTable myTab = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "bll_user_get_info";
            SqlParameter para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
            para = cmd.Parameters.AddWithValue("@uid", txtUid2.Text);
            try
            {
                TinyDAL.Exec(ref cmd, ref myTab);
                if (myTab.Rows.Count == 0)
                {
                    myTab.Clear();
                    lblError.Text = "User not found!";
                    return;
                }
                lblUserName.Text = myTab.Rows[0]["name"].ToString();
                lblOwnerOffice.Text = myTab.Rows[0]["owner_office"].ToString();
                lblIdentification.Text = myTab.Rows[0]["identification"].ToString();

                Label11.Visible = true;
                lblUserName.Visible = true;
                Label14.Visible = true;
                lblOwnerOffice.Visible = true;
                Label13.Visible = true;
                lblIdentification.Visible = true;
                btnAddExistingUser.Visible = true;
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
                return;
            }
        }
    }
}